package com.fanrui.code.message;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.fanrui.code.util.logger.Stdout;
import com.google.protobuf.Message;

import io.netty.channel.Channel;

public class PlayerSessions {

	private static ConcurrentMap<Long, PlayerSession> sessions = new ConcurrentHashMap<Long, PlayerSession>();
	
	public static PlayerSession getPlayerSession(Long playerId) {
		return sessions.get(playerId);
	}

	public static PlayerSession newPlayerSession(long playerId, Channel channel) {
		PlayerSession oldSender = sessions.get(playerId);
		if(null != oldSender) {
			if (oldSender.isSameSocket(channel)) {
				// 如果是同一个channel，发出警告后，直接返回旧的。
				Stdout.GET().warn("调用newPlayerSession方法时，返回了一个旧的PlayerSession！（应该是：没有Logout，却再次Login）{}", oldSender);
				return oldSender;
			}
			throw new IllegalStateException(String.format("玩家 PlayerSession 已存在 %d:%s ", playerId, oldSender.toString()));
		}
		PlayerSession newSender = new PlayerSession(playerId, channel);
		sessions.put(playerId, newSender);
		newSender.afterCreate();
		return newSender;
	}

	public static PlayerSession removePlayerSession(long playerId) {
		PlayerSession session = sessions.get(playerId);
		session.beforeRemove();
		return sessions.remove(playerId);
	}

	/**
	 * 业务中需要发送message的都调用此方法
	 * @param id
	 * @param build
	 */
	public static void sendPlayerMsg(Long id, Message message) {
		PlayerSession session = getPlayerSession(id);
		if(session != null) {
			session.send(message);
		}
	}

	public static Set<Long> keySet() {
		return sessions.keySet();
	}
	
	public static int onlineNum(){
		return sessions.size();
	}
}
